import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, Logger } from '@nestjs/common';
import { TokenService } from '../../modules/token/token.service';

@Injectable()
export class TokenGuard implements CanActivate {
  private readonly logger = new Logger(TokenGuard.name);

  constructor(private readonly tokenService: TokenService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.tokenService.extractTokenFromHeader(request);

    if (!token) {
      this.logger.warn('No token provided in request');
      throw new UnauthorizedException('No token provided');
    }

    const payload = this.tokenService.verifyToken(token);
    
    if (!payload) {
      this.logger.warn('Invalid token provided');
      throw new UnauthorizedException('Invalid token');
    }

    // 将解析后的用户信息附加到请求对象
    request.user = payload;
    
    return true;
  }
} 